package ajaxjs.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.sql.Connection;
import java.sql.SQLException;



import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ajaxjs.Constant;
import ajaxjs.sql.DAO;
import ajaxjs.config.Application;
import ajaxjs.data.entry.Entry;
import ajaxjs.data.service.BaseService;

public class BaseServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	private Map<String, String> initParamsMap = new HashMap<String, String>();	
	/**
	 * 初始化所有 JSON 接口
	 * 为了方便测试，可以每次请求加载一次 js 文件，于是重载了一个子方法 private void init(String Rhino_Path)
	 */
	public void init(ServletConfig config) throws ServletException {
		init(Application.Rhino_Path);
		
		// 遍历注解的配置，需要什么类，收集起来，放到一个 hash 之中
		Enumeration<String> initParams = config.getInitParameterNames();
		while (initParams.hasMoreElements()) {
			String	initParamName 	= initParams.nextElement(),
					initParamValue 	= config.getInitParameter(initParamName);
			
//			System.out.println("initParamName：" + initParamName + ", initParamValue:" + initParamValue);
			initParamsMap.put(initParamName, initParamValue);
		}
	}
	
	/**
	 * 初始化 js 引擎
	 * @param Rhino_Path
	 */
	private void init(String Rhino_Path){
		System.out.println(Constant.ConsoleDiver);
		System.out.println("初始化业务规则引擎（Powered by Rhino）");
		Application.jsRuntime.put("jsEngine",   Application.jsRuntime);		// 把 js engine 放在 js 自身里面
		Application.jsRuntime.put("urlMapping", initParamsMap);	// 绑定数据库连接对象
		
		Application.jsRuntime.load(Rhino_Path + "/sql/reader.js");
		Application.jsRuntime.load(Rhino_Path + "/sql/util.js");
		Application.jsRuntime.load(Rhino_Path + "/sql/writer.js");
		Application.jsRuntime.load(Rhino_Path + "/route/controller.js");	
	}
	
	public static String getConnStr() {
//		return "jdbc/mysql_deploy";
		return "jdbc/sqlite";
//		return !Application.isDebug ? "jdbc/sqlite" : "jdbc/sqlite_deploy";
	}
	private void doAction(HttpServletRequest request, HttpServletResponse response){
		long t1 = System.currentTimeMillis();  
		
		// 为避免重启服务器，调试模式下再加载 js
		if(Application.isDebug)init(Application.Rhino_Path);
		
		ajaxjs.net.Request.setUTF8(request, response);
		response.setContentType("application/json");
		
//		System.out.println(ajaxjs.net.Request.getCurrentPage_url(request));/

		Connection jdbcConn = DAO.getConn(getConnStr());

		try {
			Object obj = Application.jsRuntime.call("bf_controller_init", request, jdbcConn);
			if(obj != null)
				response.getWriter().println(obj.toString());
		} catch (Exception e) {
			e.printStackTrace();
			ajaxjs.Util.catchException(e, "调用 bf.controller.init(); 失败！");
		}
		
		output(request, response);
		
		try {
			if(jdbcConn != null)jdbcConn.close();		
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		long t2 = System.currentTimeMillis();  
		
		System.out.println(Constant.ConsoleDiver);
		System.out.println("关闭数据库连接成功！完成请求时间：" + (t2 - t1) + "ms");
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { 
		doAction(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response){
		doAction(request, response);
	} 

	public void doPut(HttpServletRequest request, HttpServletResponse response){
		doAction(request, response);
	} 
	
	public void doDelete(HttpServletRequest request, HttpServletResponse response){
		doAction(request, response);
	} 
	public static BaseService bs = new BaseService(){
		@Override
		public Entry getPojo() {
			return null;
		}

		@Override
		public String getName() {
			return null;
		}

		@Override
		public String getId() {
			return null;
		}

		@Override
		public String getTableName() {
			return null;
		}
	};
	public static void output(HttpServletRequest request, HttpServletResponse response){
		PrintWriter out = null;
		
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(request.getAttribute("isRawOutput") != null && (boolean)request.getAttribute("isRawOutput")){
			// 直接输出 json，适合单个记录
			if(request.getAttribute("msg") != null)
				out.write(request.getAttribute("msg").toString());
			
		}else if(request.getAttribute("js_err") != null){
			// 有  js 错误！
			out.write(bs.showException(request.getAttribute("js_err").toString()));
		}else if(request.getAttribute("errMsg") != null){
			// 有错误！
			out.write(bs.showException(request.getAttribute("errMsg").toString()));
		}else if(request.getAttribute("msg") != null){
			out.write(bs.printOk(request.getAttribute("msg").toString()));
		}
		//return msg;
	}
}